<?

 define ('MODEL_ORDER_ADD', 	'INSERT INTO `orders` (`id`, `date` ,`user_id` ,`good_id`, `colors`,`price`, `collections` ,`quantity`, `payment`, `delivery`, `note`, `state`) VALUES (?, now() , ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)');
 define ('MODEL_ORDER_FIND',	'SELECT `orders`.`id` , `users`.`realname` , sum( `orders`.`price` * `orders`.`quantity` ) as `sum`, `orders`.`date`
FROM `orders` , `goods` , `users`
WHERE `orders`.`user_id` = `users`.`id`
AND `orders`.`good_id` = `goods`.`id`
AND `orders`.`state` = ?
GROUP BY (
`orders`.`id`
)');

 define ('MODEL_ORDER_MAX_ID',		'SELECT max(id) as `id` FROM `orders`');

 define ('MODEL_ORDER_FIND_ONE',	'SELECT *
FROM `orders` , `goods` , `users`
WHERE `orders`.`user_id` = `users`.`id`
AND `orders`.`good_id` = `goods`.`id`
AND `orders`.`id` = ?
');

 define ('MODEL_ORDER_UPDATE_STATE',	'UPDATE `orders` SET `state` = ? WHERE `id` = ?');

 class Model_Order extends Models_Base {
	function add($user_id,$args) {
		
		$basket = new Model_Basket();

//		print_r($this->getNewId());
		$id = $this->getNewId()->id + 1;
//		error_log("NEW ID: $id ");

		$info = $args[company].", ".$args[info];

		foreach($basket->get($user_id) as $key => $value ) {
			$this->insertRow(MODEL_ORDER_ADD,array($id, $user_id, $key, join(", ",$value[colors]), $value[price], $value[quantity], $value[quantity]*count($value[colors])*$value[sizes], $args[payment], $args[delivery], $info));
		}
		
		$basket->clear($user_id);
		
		return $id;
	}
	
	function find($args = null) {
		
		
		$state = 1;
		
		if($args[state] === 'processed')
			$state = 2;
		else if($args[state] === 'deleted')
			$state = 4;
			
			
		if(isset($args[id]))
			return $this->getAll(MODEL_ORDER_FIND_ONE,array($args[id]));
		else
			return $this->getAll(MODEL_ORDER_FIND,array($state));
	} 
	
	private function getNewId() {
		return $this->getRow(MODEL_ORDER_MAX_ID,array());
	}
	
	function process($id) {
		return $this->execute(MODEL_ORDER_UPDATE_STATE,array(2,$id));
	}
	
	function delete($id) {
		return $this->execute(MODEL_ORDER_UPDATE_STATE,array(4,$id));
	}
}

?>